<template>
  <div>
    <div class="content">
      <filterTitle @query="query" @reset="reset" class="title" :form="form" :formData="formData">
      </filterTitle>

      <LsdTable slot="yjrwlb" :paginationAtrrs="table.paginationAtrrs" @pageChange="handleSizeChange"
        :compRef="table.compRef" ref="yjrwlb" :columns="table.columns" :title="table.title" :actions="table.actions"
        :tableData="table.tableData" :tableAttr="table.tableAttr" :isShowPage="table.isShowPage"
        :isSelectFlag="table.isSelectFlag" :isSequenceFlag="table.isSequenceFlag" @onActionClick="onActionClick" />
    </div>
    <!-- 新增班次配置弹窗 -->
    <el-dialog :visible.sync="dialogVisible" :close-on-click-modal="false" :close-on-press-escape="false">
      <div slot="title" class="header-title" :style="{ 'background': '#5077ff', 'color': 'white' }">
        <div style="padding:15px 20px;">{{ title }}</div>
      </div>
      <el-form :model="formAdd" label-width="140px" :rules="rulesForm" ref="rulesForm">
        <el-form-item label="班次类别：" prop="shiftCategory" :rules="rulesForm.shiftCategory">
          <el-select v-model="formAdd.shiftCategory" placeholder="请选择班次类别" :disabled="disabled" style="width: 100%;"
            @change="shiftChange">
            <el-option v-for="(item, i) in formData[0].options" :key=i :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="item.label + '：'" v-for="(item, index) in formList" :key="index" :prop="item.id"
          :rules="rulesForm.dwmc">
          <LsdForm :compData="item" :form="formAdd" @node-click="handleSelectTree(arguments, item)" />
        </el-form-item>
        <el-form-item label="班次配置：" prop="bcpz">
          <el-table :data="formAdd.bcpz" border :header-cell-style="{ background: '#b1c8f9', color: '#000000' }">
            <el-table-column label="班次名称" prop="shiftName" align="center" width="200">
              <template slot-scope="scope">
                <el-form-item :prop="'bcpz.' + scope.$index + '.shiftName'" :rules="rulesForm.shiftName">
                  <!-- @change="leaveOptions" -->
                  <el-select v-model="scope.row.shiftName" @visible-change="leaveOptions">
                    <el-option v-for="(item, index) in optionList" :key="index" :value="item.label"
                      :label="item.label"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="班次时间" prop="shiftTime" align="center" class="shiftTime">
              <template slot-scope="scope">
                <el-form-item :prop="'bcpz.' + scope.$index + '.startTime'" :rules="rulesForm.startTime">
                  <el-time-select :disabled="scope.row.startFlag" placeholder="起始时间" value-format='HH:mm'
                    v-model="scope.row.startTime" :picker-options="{ start: '00:00', step: '00:30', end: '23:30' }"
                    @change="startTimehange(scope.$index, scope.row)"> </el-time-select>
                </el-form-item>
                <span style="margin: 0 20px;">——</span>
                <el-form-item :prop="'bcpz.' + scope.$index + '.endTime'" :rules="rulesForm.endTime">
                  <el-time-select :disabled="scope.row.endFlag" placeholder="结束时间" value-format='HH:mm'
                    v-model="scope.row.endTime" :picker-options="{ start: '00:00', step: '00:30', end: '23:30' }"
                    @change="endTimeChange(scope.$index, scope.row)"> </el-time-select>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="是否启用：" prop="status">
          <el-switch v-model="formAdd.status" active-text="是" inactive-text="否"></el-switch>
        </el-form-item>
      </el-form>
      <div class="footer-btn">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// import moment from "moment";
import { unitList, getDutyShiftList, savaDutyList, deletedDutyById } from "@/api/SystemConfig/dutyConfig.js";
export default {
  data() {
    return {
      title: "",
      shiftList: [],
      disabled: false,
      params: {
        pageNum: 1,
        pageSize: 1000
      },
      formAdd: {
        dwmc: "",
        shiftCategory: "",
        bcpz: [],
        status: false
      },
      rulesForm: {
        shiftCategory: [
          { required: true, message: "请选择班次类别", trigger: "change" }
        ],
        shiftName: [
          { required: true, message: "请选择班次名称", trigger: "change" }
        ],
        endTime: [
          { required: true, message: "请选择班次时间", trigger: "change" }
        ],
        startTime: [
          { required: true, message: "请选择班次时间", trigger: "change" }
        ],
        dwmc: [
          { required: true, message: "请选择单位名称", trigger: "change" }
        ],
        bcpz: [
          { required: true }
        ],
        status: [
          // { required: true }
        ]
      },
      dialogVisible: false,
      table: {
        isSelectFlag: true,
        compRef: "yjrwlb",
        isSequenceFlag: false,
        isShowPage: true,
        resetFlag: true,
        loading: false,
        title: "班次配置",
        actions: [
          {
            id: "add",
            text: "新增",
            type: "primary",
            btnAttr: { size: "small" }
          },
          {
            id: "expor",
            text: "导出",
            btnAttr: { size: "small" }
          }
        ],
        tableData: [],
        columns: [
          {
            prop: "xh",
            label: "序号",
            align: "center",
            width: "100"
          },
          {
            prop: "shiftCategory",
            label: "班次类别",
            align: "center"
          },
          {
            prop: "shiftName",
            label: "班次名称",
            align: "center"
          },
          {
            prop: "shiftTime",
            label: "班次时间",
            align: "center"
          },
          {
            prop: "status",
            label: "启用状态",
            align: "center",
            width: "100"
          },
          {
            prop: "cz",
            label: "操作",
            align: "center",
            fixed: "right",
            "min-width": "120px",
            render: (h, scope) => {
              return (
                <div>
                  <span style='color:#3561fd;cursor:pointer;margin:0 10px'{...{
                    on: {
                      click: () => {
                        this.add(scope.row);
                      }
                    }
                  }}>
                    编辑
                  </span>
                  <span style='color:#3561fd;cursor:pointer;margin:0 10px' {...{
                    on: {
                      click: () => {
                        const option = this.chooseItem(scope.row.shiftCategory);
                        console.log(option);
                        this.$confirm("确定删除吗？", "提示", {
                          confirmButtonText: "确定",
                          cancelButtonText: "取消",
                          type: "warning"
                        }).then(async () => {
                          const data = [];
                          option.map(item => {
                            return data.push(item.id);
                          });
                          await deletedDutyById(data);
                          this.getPageList();
                          this.$message({
                            message: "删除成功",
                            type: "success"
                          });
                        });
                      }
                    }
                  }}>
                    删除
                  </span>
                  <span style='color:#3561fd;cursor:pointer;margin:0 10px'{...{
                    on: {
                      click: () => {
                        const option = this.chooseItem(scope.row.shiftCategory);
                        console.log(option);
                        this.$confirm("确定启用吗？", "提示", {
                          confirmButtonText: "确定",
                          cancelButtonText: "取消",
                          type: "warning"
                        }).then(() => {
                          const data = option.map(item => {
                            return {
                              id: item.id,
                              status: "0"
                            };
                          });
                          this.savaDutyList(data, "已启用");
                        });
                      }
                    }
                  }}>
                    启用
                  </span>
                  <span style='color:#eb3434;cursor:pointer;margin:0 10px' {...{
                    on: {
                      click: () => {
                        const option = this.chooseItem(scope.row.shiftCategory);
                        console.log(option);
                        this.$confirm("确定停用吗？", "提示", {
                          confirmButtonText: "确定",
                          cancelButtonText: "取消",
                          type: "warning"
                        }).then(() => {
                          const data = option.map(item => {
                            return {
                              id: item.id,
                              status: "1"
                            };
                          });
                          this.savaDutyList(data, "已停用");
                        });
                      }
                    }
                  }}>
                    停用
                  </span>
                </div >
              );
            }
          }

        ],
        tableAttr: {
          stripe: false,
          border: true,
          fit: true,
          "span-method": ({ row, column, rowIndex, columnIndex }) => {
            let contactDot = 0;
            let xh = 1;
            const [spanArr] = this.table.tableData.reduce(([arr1], item, index) => {
              if (index === 0) {
                arr1.push(1);
                item.xh = xh;
              } else {
                if (item.shiftCategory === this.table.tableData[index - 1].shiftCategory) {
                  arr1[contactDot] += 1;
                  arr1.push(0);
                  item.xh = xh;
                } else {
                  contactDot = index;
                  arr1.push(1);
                  xh++;
                  item.xh = xh;
                }
              }
              return [arr1];
            }, [[]]);
            if ([0, 1, 2, 5, 6].includes(columnIndex)) {
              // const arr = columnIndex === 0 ? spanArr : spanArrs;
              const value = spanArr[rowIndex];
              return {
                rowspan: value || 0,
                colspan: 1
              };
            } else {
              return {
                rowspan: 1,
                colspan: 1
              };
            }
          },
          "show-header": true,
          "highlight-current-row": true,
          "cell-style": {
            "font-size": "16px"
          },
          "header-cell-style": {
            "text-align": "center",
            "background-color": "#B1C8F9",
            border: "1px solid #ccc",
            color: "#333333",
            "font-size": "18px"
          }
        },
        // 分页信息
        paginationAtrrs: {
          total: 0,
          "background": true,
          layout: "prev, pager, next",
          "current-page": 1,
          "page-size": 1000
        }
      },
      form: {
        shiftCategory: "",
        status: ""
      },
      formData: [
        {
          elType: "select",
          label: "班次类别",
          id: "shiftCategory",
          attrs: {
            value: "",
            size: "small",
            clearable: true,
            filterable: true,
            "collapse-tags": true
          },
          options: [
            {
              label: "两班",
              value: "两班"
            },
            {
              label: "三班",
              value: "三班"
            }
          ]
        },
        {
          elType: "select",
          label: "启用状态",
          id: "status",
          attrs: {
            value: "",
            size: "small",
            clearable: true,
            filterable: true,
            "collapse-tags": true
          },
          options: [
            {
              label: "已停用",
              value: "1"
            },
            {
              label: "已启用",
              value: "0"
            }
          ]
        }
      ],
      optionList: [],
      option: [
        {
          label: "早班",
          value: "1"
        },
        {
          label: "中班",
          value: "2"
        },
        {
          label: "晚班",
          value: "3"
        }
      ],
      formList: [
        {
          elType: "lsdTree",
          id: "dwmc",
          name: "orgName",
          label: "单位名称",
          treeRef: "treeRef",
          keyWord: "keyWord",
          attrs: {
            value: "",
            clearable: true,
            "collapse-tags": true,
            disabled: false
          },
          options: {
            attrs: {
              value: ""
            }
          },
          treeData: {
            attrs: {
              data: []
            },
            props: {
              children: "children",
              label: "orgName",
              value: "id"
            }
          }
        }
      ]
    };
  },
  mounted() {
    this.getPageList();
    this.getUnitList();
  },
  methods: {
    shiftChange(e) {
      this.formAdd.bcpz.length = 0;
      const obj = {
        shiftName: "",
        startTime: "",
        endTime: "",
        startFlag: false,
        endFlag: false
      };
      const index = e == "两班" ? 2 : 3;
      for (let i = 0; i < index; i++) {
        this.formAdd.bcpz.push(JSON.parse(JSON.stringify(obj)));
      }
    },

    endTimeChange(index, row) {
      if (this.formAdd.bcpz.length != (index + 1)) {
        this.formAdd.bcpz[index + 1].startFlag = !!row.endTime;
        this.formAdd.bcpz[index + 1].startTime = row.endTime;
      }
    },
    startTimehange(index, row) {
      if (index != 0) {
        this.formAdd.bcpz[index - 1].endFlag = !!row.startTime;
        this.formAdd.bcpz[index - 1].endTime = row.startTime;
      }
    },
    // 获取班次配置信息
    async getPageList(data) {
      const res = await getDutyShiftList(Object.assign(this.params, data));
      res.data.forEach((item, i) => {
        item.status = item.status == "0" ? "已启用" : item.status == "1" ? "已停用" : "";
      });
      this.table.tableData = res.data;
      console.log(this.table.tableData, "123");
      this.table.paginationAtrrs.total = res.total;
    },
    // 获取单位名称
    async getUnitList() {
      const res = await unitList();
      console.log(res);
      this.formList[0].treeData.attrs.data = res;
    },

    chooseItem(e) {
      const arr = this.table.tableData.filter(item => {
        return e == item.shiftCategory;
      });
      return arr;
    },

    // 班次名称限制
    leaveOptions() {
      const arr = [];
      this.formAdd.bcpz.forEach(item => {
        arr.push(item.shiftName);
      });
      this.optionList = this.option.filter(item => {
        return !(arr.includes(item.label));
      });
    },

    handleSizeChange(val) {
      this.params.pageNum = val["current-page"];
      this.params.pageSize = val["page-size"];
      this.getPageList();
    },
    onActionClick(item) {
      this[item.id]();
    },
    // 新增
    add(row) {
      this.dialogVisible = true;
      this.disabled = false;
      this.title = "新增班次配置";
      // 编辑
      if (row) {
        console.log(row);
        this.title = "编辑班次配置";
        this.disabled = true;
        this.formList[0].attrs.disabled = true;
        const shiftOptions = this.chooseItem(row.shiftCategory);
        // console.log(shiftOptions, "shiftOptions");
        const regex = /(?<=\()(.+?)(?=\))/g;
        this.formAdd.dwmc = shiftOptions[0].shiftCategory.match(regex)[0];
        this.formAdd.status = shiftOptions[0].status == 0;
        this.formAdd.shiftCategory = shiftOptions[0].shiftCategory.substring(0, 2);
        this.formAdd.bcpz = shiftOptions.map(item => {
          const a = item.shiftTime.split("-");
          return {
            id: item.id,
            shiftName: item.shiftName,
            startTime: a[0],
            endTime: a[1]
          };
        });
        console.log(this.formAdd.bcpz, "this.formAdd.bcpz");
      }
    },
    // 保存
    async savaDutyList(data, msg) {
      try {
        await savaDutyList(data);
        this.$message({
          message: msg,
          type: "success"
        });
        this.dialogVisible = false;
        this.getPageList();
      } catch (error) {
        console.log(error);
      }
    },

    save() {
      // 非空校验
      this.$refs.rulesForm.validate((valid => {
        if (!valid) return;
        // 班次时间限制
        const sum = this.formAdd.bcpz.reduce((total, picker) => {
          const startHour = parseInt(picker.startTime.split(":")[0]);
          const startMinute = parseInt(picker.startTime.split(":")[1]);
          let endHour = parseInt(picker.endTime.split(":")[0]);
          const endMinute = parseInt(picker.endTime.split(":")[1]);
          // 处理开始时间大于结束时间的情况
          if (startHour > endHour) {
            endHour += 24;
          }
          const duration = (endHour - startHour) + (endMinute - startMinute) / 60;
          return total + duration;
        }, 0);
        // console.log(sum, "----sum");
        if (sum != 24) {
          alert("选择的时间总和必须等于24小时");
          return;
        }
        // 执行保存操作
        const params = this.formAdd.bcpz.map(item => {
          return {
            id: item.id,
            shiftCategory: `${this.formAdd.shiftCategory}(${this.formAdd.dwmc})`,
            status: this.formAdd.status == false ? 1 : 0,
            shiftName: item.shiftName,
            shiftTime: item.startTime + "-" + item.endTime
          };
        });
        console.log(params, "params");
        this.savaDutyList(params, "添加成功");
      }));
    },
    // 查询
    query() {
      this.params.pageSize = 1000;
      this.params.pageNum = 1;
      this.getPageList(this.form);
    },
    handleSelectTree(val, item) {
      this.formAdd.dwmc = val[0].orgName;
    },
    // 重置
    reset() {
      this.$refs.form.resetFields();
      this.getPageList();
    },
    cancel() {
      this.dialogVisible = false;
      this.$refs.rulesForm.resetFields();
    }
  }
};
</script>
<style lang="less" scoped>
.content {
  padding: 20px;

  .tableTitle {
    display: flex;
    justify-content: center;
  }
}

.footer-btn {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

:deep(.el-dialog__header) {
  padding: 0;
}

:deep(.el-table td.el-table__cell div) {
  display: flex;
  justify-content: center;
}

:deep(.el-select) {
  width: 100%;
}
</style>
